﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.Samples.Kinect.SkeletonBasics;

    class Client
    {
        private int port;
        private String address;
        private TcpClient tcpClient;
        private Thread clientThread;
        private int angularPosition = 0;
        private String jointPositionString;
        private String inferredJointPositions;
        private bool isConnected;

        public Client()
        {
            tcpClient = new TcpClient();
            String address = "";

            //only used for server computer
            System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());

            foreach (System.Net.IPAddress add in ipEntry.AddressList) {

                if (add.AddressFamily.ToString() == "InterNetwork") {

                    address = add.ToString();
                }
            }

            port = 1241;
            tcpClient.Connect(address, port);

            Console.WriteLine("Connected to Kinect Server");

            clientThread = new Thread(new ThreadStart(dataExchange));
            clientThread.Start();
            clientThread.IsBackground = true;

        }

        private void dataExchange()
        {


            NetworkStream clientStream = tcpClient.GetStream();
            byte[] sentMessage = new byte[0];
            ASCIIEncoding encoder = new ASCIIEncoding();
            sentMessage = encoder.GetBytes("P" + angularPosition.ToString());
            clientStream.Write(sentMessage, 0, sentMessage.Length);

            isConnected = true;

            byte[] receivedMessage = new byte[4096];
            int bytesread;

            while (true)
            {
                try
                {
                    bytesread = clientStream.Read(receivedMessage, 0, 4096);
                }
                catch
                {
                    Console.WriteLine("No server");
                    break;
                }

                if (bytesread == 0)
                {
                    Console.WriteLine("Client has disconnected");
                    break;
                }

                encoder = new ASCIIEncoding();

                if (char.ConvertFromUtf32(receivedMessage[0]).Equals("0"))
                {
                    sentMessage = encoder.GetBytes(jointPositionString + ";");
                }
                clientStream.Write(sentMessage, 0, sentMessage.Length);
                clientStream.Flush();

            }
            clientStream.Flush();
            clientStream.Close();
            tcpClient.Close();
        }

        public void setJointPositionString(String s)
        {
            jointPositionString = s;
        }

    }
